package com.xianggu.trafficLimiter.impl;

import com.xianggu.trafficLimiter.TrafficLimiter;

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author chengjy
 * @date 2025/3/25
 */

public class DateWindowBucketLimiter implements TrafficLimiter {
    private AtomicLong count = new AtomicLong(0);// 当前请求数
    private long limitNum = 10; // 每秒中最大QBS
    private long interval = 1000L; // 时间窗口时长
    private LinkedList<Long> intervalList = new LinkedList<>(); // 时间窗口时长

    private volatile boolean threadRunning = true;

    public DateWindowBucketLimiter() {
        intervalList.addLast(0L);
        new Thread(() -> {
            long windowSize = interval / limitNum;
            while (threadRunning) {
                try {
                    Thread.sleep(windowSize);
                    if (intervalList.size() > windowSize) {// 移除最老的
                        count.set(count.get() - intervalList.removeFirst());
                    }
                    System.out.println("移动窗口-当前请求数："+count.get());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @Override
    public synchronized boolean limit() {
        if(count.get() + 1 > limitNum){
            return true;
        }
        intervalList.set( intervalList.size() - 1, intervalList.peekLast() + 1);
        count.incrementAndGet();
        return false;
        }

    @Override
    public void stopThread() {
        threadRunning = false;
    }
}
